package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ApArticleFeign;
import com.usian.admin.feign.WmnewsFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.common.aliyun.scan.GreeTextScan;
import com.usian.common.aliyun.scan.GreenImageScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.admin.pojos.AdSensitive;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AutoAuditServiceImpl extends BaseServiceImpl<AdSensitiveMapper, AdSensitive> {
    @Autowired
    private WmnewsFeign wmnewsFeign;
    @Autowired
    private ApArticleFeign apArticleFeign;
    @Autowired
    private GreeTextScan textScan;
    @Autowired
    private GreenImageScan imageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private AdChannelMapper channelMapper;
    private Boolean flag = false;
    private String reason;
    @Value("${fdfs.url}")
    private String dfsUrl;
    @GlobalTransactional
    public ResponseResult autoExamine(Integer id){
        if (id==null) return errorParam;
        WmNews wmNews = wmnewsFeign.findById(id);
        WmNews news = new WmNews();
        if (wmNews==null) return errorParam;
        news.setId(wmNews.getId());
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())){
            if (wmNews.getPublishTime().getTime()< System.currentTimeMillis()){
                news.setStatus(WmNews.Status.PUBLISHED.getCode());
                wmnewsFeign.update(news);
                saveArticleScan(wmNews);
                return successParam;
            }
        }
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            String content = wmNews.getContent();//获取文章内容
            List<Map> list = JSON.parseArray(content, Map.class);
            StringBuffer buffer = new StringBuffer();
            List<String> imgUrl = new ArrayList<>();
            for (Map map : list) {
                String value = map.get("value").toString();
                if (map.get("type").equals("text")){
                    buffer.append(value);
                }else {
                    imgUrl.add(value);
                }
            }
            if (wmNews.getType()!=0) Collections.addAll(imgUrl, wmNews.getImages().split(","));
            Map map;
            try {
                //文本审核
                map = textScan.greeTextScan(content);
                reason = "文本";
                flag = AliyunScan(map,reason,news);//文本审核是否通过
                if (flag){
                    //图片审核
                    ArrayList<byte[]> imgList = new ArrayList<>();
                    for (String s : imgUrl) {
                        s = s.replace(dfsUrl, "");
                        int i = s.indexOf("/");
                        String groupName = s.substring(0, i);
                        String path = s.substring(i + 1);
                        imgList.add(fastDFSClient.download(groupName, path));
                    }
                    map = imageScan.imageScan(imgList);
                    reason = "图片";
                    flag = AliyunScan(map,reason,news);//图片审核是否通过
                }
                if (flag){
                    //敏感词审核
                    List<String> sensitives = baseMapper.findList();
                    SensitiveWordUtil.initMap(sensitives);
                    Map<String, Integer> sensitivesMap = SensitiveWordUtil.matchWords(buffer.toString());
                    if (sensitivesMap.size()>0){
                        reason = "铭感词不通过";
                        news.setReason(reason);
                        news.setStatus(WmNews.Status.FAIL.getCode());
                        wmnewsFeign.update(news);
                        flag = false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                flag =false;
            }
        }
        if (flag){//新闻审核通过
            //修改新闻状态
            news.setReason("审核通过");
            news.setStatus(WmNews.Status.PUBLISHED.getCode());
            ApArticle apArticle = saveArticleScan(wmNews);
            news.setArticleId(apArticle.getId());
            wmnewsFeign.update(news);
        }
        return flag?successParam:ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,reason+"审核失败");
    }
    private Boolean AliyunScan(Map map,String reason,WmNews news){
        if (!map.get("suggestion").equals("pass")){
            if (map.get("suggestion").equals("block")){//有敏感词不通过
                news.setReason(reason+"违规");
                news.setStatus(WmNews.Status.FAIL.getCode());
            }
            if (map.get("suggestion").equals("review")){//需要人工审核
                news.setReason(reason+"需要人工审核");
                news.setStatus(WmNews.Status.ADMIN_AUTH.getCode());
            }
            wmnewsFeign.update(news);
            return false;
        }
        return true;
    }
    private ApArticle saveArticleScan(WmNews wmNews){
        // 添加文章
        ApArticle apArticle = saveArticle(wmNews);
        //添加ap_article_config
        saveConfig(apArticle.getId());
        //添加ap_article_config
        saveContent(wmNews,apArticle.getId());
        return apArticle;
    }
    private ApArticle saveArticle(WmNews wmNews){
        ApArticle article = new ApArticle();
        ApAuthor author = apArticleFeign.findByUserId(wmNews.getUserId());
        AdChannel channel = channelMapper.selectById(wmNews.getChannelId());
        article.setTitle(wmNews.getTitle());
        if (author!=null)article.setAuthorId(author.getId().longValue());
        if (author!=null)article.setAuthorName(author.getName());
        if (channel!=null)article.setChannelId(channel.getId());
        if (channel!=null)article.setChannelName(channel.getName());
        article.setLayout(wmNews.getType());
        article.setFlag((byte)0);
        article.setImages(wmNews.getImages());
        article.setCreatedTime(new Date());
        article.setPublishTime(new Date());
        ApArticle apArticle = apArticleFeign.save(article);
        return apArticle;
    }
    private void saveConfig(Long id){
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(id);
        config.setIsComment(true);
        config.setIsForward(true);
        config.setIsDelete(false);
        config.setIsDown(false);
        apArticleFeign.save(config);
    }
    private void saveContent(WmNews wmNews,Long id){
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(id);
        content.setContent(wmNews.getContent());
        apArticleFeign.save(content);
    }
    public ResponseResult updateStatus(Integer id,Short status){
        if (id==null)return errorParam;
        WmNews wmNews = new WmNews();
        if (wmNews==null) return notExit;
        wmNews.setId(id);
        wmNews.setStatus(status);
        if (status.equals(2)){
            reason = "审核不通过";
        }else {
            reason="审核通过";
        }
        wmNews.setReason(reason);
        wmnewsFeign.update(wmNews);
        return successParam;
    }
}
